namespace ScrumSprintMonitor.TestbenchApp
{
	#region #using Directives

	using System.IO;
	using System.Linq;
	using System.Reflection;

	using Extensibility;

	using Infrastructure;
	using Infrastructure.Configuration;

	using Microsoft.Practices.ServiceLocation;

	#endregion

	public class AddInHost<TAddIn> : IAddInHost<TAddIn>
		where TAddIn : ScrumSprintMonitorAddIn
	{
		private readonly ILogger<AddInHost<TAddIn>> logger;
		private readonly IServiceLocator serviceLocator;
		private string outputDirectory;

		public AddInHost(IServiceLocator serviceLocator, ILogger<AddInHost<TAddIn>> logger)
		{
			this.serviceLocator = serviceLocator;
			this.logger = logger;
		}

		#region IAddInHost<TAddIn> Members

		public string GetOutputDirectory()
		{
			if (string.IsNullOrEmpty(this.outputDirectory))
			{
				var sprintConfiguration = this.serviceLocator.GetInstance<ISprintConfiguration>();
				this.outputDirectory = Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Output"),
				                                    sprintConfiguration.ProjectName);

				string addInName = null;
				var attribute = typeof(TAddIn).GetCustomAttributes(typeof(AddInAttribute), true).FirstOrDefault() as AddInAttribute;
				if (attribute != null)
				{
					addInName = attribute.Name;
				}

				if (!string.IsNullOrEmpty(addInName))
				{
					this.outputDirectory = Path.Combine(this.outputDirectory, addInName);
				}

				if (!Directory.Exists(this.outputDirectory))
				{
					this.logger.Info("Creating output folder {0}.", this.outputDirectory);

					Directory.CreateDirectory(this.outputDirectory);
				}
			}

			return this.outputDirectory;
		}

		#endregion
	}
}